/**
 * 租务&设备 状态
 */
import * as types from '../types'

const cache = JSON.parse(sessionStorage.homeStateCache || '{}')

const state = {
  currentTab: '/',
  openedTab: Array.isArray(cache.openedTab) ? cache.openedTab : []
}

const mutations = {
  [types.SET_CURRENT_TAB] (state, val) {
    state.currentTab = val
  },
  [types.REMOVE_TAB] (state, index) {
    state.openedTab.splice(index, 1)
    setStateCache(state)
  },
  [types.ADD_TAB] (state, home) {
    state.openedTab = [...state.openedTab, home]
    setStateCache(state)
  },
  [types.CLEAN_TAB] (state) {
    state.currentTab = '/'
    state.openedTab = []
  }
}

const actions = {
  setCurrentTab ({ commit }, val) {
    commit(types.SET_CURRENT_TAB, val)
  },
  addTab ({ commit, state }, home) {
    return new Promise(resolve => {
      commit(types.SET_CURRENT_TAB, '/' + home.id)
      const homeIds = state.openedTab.map(home => home.id)
      if (!homeIds.includes(home.id)) {
        commit(types.ADD_TAB, home)
      }
      resolve()
    })
  },
  /**
     * 移除房屋标签，找出要删除的房屋index后删除，更改currentTab，
     * 返回新的路径值到组件中跳转
     * @param {*} param0
     * @param {*} id 要移除的房屋id
     * @return Promise 跳转的路径
     */
  removeTab ({ commit, dispatch, state }, id) {
    return new Promise(resolve => {
      let lastTabId
      let _id = id.replace('/', '')

      state.openedTab.forEach((tab, index) => {
        if (Number(tab.id) === Number(_id)) {
          // eslint-disable-line
          lastTabId = (state.openedTab[index - 1] && state.openedTab[index - 1].id) || ''
          commit(types.REMOVE_TAB, index)
        }
      })
      resolve('/' + lastTabId)
    })
  },
  // 跳转到其他顶级路由时调用，清除房屋信息
  cleanHomeStateCache ({ commit }) {
    return new Promise(resolve => {
      cleanStateCache()
      commit(types.CLEAN_TAB)
      resolve()
    })
  },
  /**
     * 进入房屋获取全部home之后，对比房屋id获取激活的home对象，填入tab中
     * @param {} param0
     * @param {target:[number, string], home: object[]} data
     */
  getHomeByUrl ({ dispatch, state }, data) {
    // console.log(data.target)
    if (data.target && !hasKey(state.openedTab, data.target)) {
            const home = data.homes.filter(home => home.id == data.target)[0]; // eslint-disable-line
      dispatch('addTab', home)
    }
  }
}

const getters = {
  currentTab: state => state.currentTab,
  openedTab: state => state.openedTab
}

/**
 * 缓存当前state到sessionStorage
 * @param {object} state
 */
function setStateCache (state) {
  const cache = {
    // currentTab: state.currentTab,
    openedTab: state.openedTab
  }
  sessionStorage.setItem('homeStateCache', JSON.stringify(cache))
}

/**
 * 清除sessionStorage
 */
function cleanStateCache () {
  sessionStorage.setItem('homeStateCache', JSON.stringify({}))
}

function hasKey (arr, id) {
    return arr.filter(item => item == id)[0]; // eslint-disable-line
}

export default {
  state,
  actions,
  getters,
  mutations
}
